# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from flask import render_template, request, redirect, url_for, session

from login_manager import login_required
from modelos import Professor, Disciplina, Aluno, AlunoDisciplina, AlunoAula

from __init__ import app

#exclui um aluno do banco de dados
@app.route("/excluir_aluno/<int:id>")
@login_required
def excluir_aluno(id):

    a = Aluno.get(Aluno.id == id)

    for ad in AlunoDisciplina.select().where(AlunoDisciplina.aluno == a):
        ad.delete_instance()

    for aa in AlunoAula.select().where(AlunoAula.aluno == a):
        aa.delete_instance()

    a.delete_instance()

    return redirect(url_for("form_add_alunos"))

#cadastrar uma nova disciplina
@app.route("/form_add_alunos", methods=['GET', 'POST'])
@login_required
def form_add_alunos():

    if request.method == 'POST':

        nome = request.form["nome"]
        ra = request.form["ra"]

        Aluno.create(nome=nome, ra=ra)

        return redirect(url_for("form_add_alunos"))

    else:

        alunos = Aluno.select().order_by(Aluno.nome)

        return render_template("form_add_alunos.html", alunos=alunos)

#desvincular aluno de disciplina
@app.route("/desvincular_aluno/aluno/<int:aluno_id>/disciplina/<int:disciplina_id>")
@login_required
def desvincular_aluno(aluno_id, disciplina_id):

    aluno = Aluno.get(Aluno.id == aluno_id)

    p = Professor.get(Professor.id == session["user_id"])

    disciplina = Disciplina.get(Disciplina.id == disciplina_id, Disciplina.professor == p)

    aluno_aula = AlunoAula.select().where(AlunoAula.aluno == aluno)

    # Remove as presenças
    for a in aluno_aula: a.delete_instance()

    for a in AlunoDisciplina.select().where(AlunoDisciplina.aluno == aluno, AlunoDisciplina.disciplina == disciplina):
        a.delete_instance()

    return redirect(url_for("ver_disciplina", id=disciplina_id))